package com.svse.annotation;

import com.alibaba.fastjson.JSONObject;
import com.svse.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Copyright 上海危网信息科技有限公司版权所有
 * @company wwsoft
 * @Date 2019/11/21 15:02
 */
@Aspect
@Component
@Slf4j
public class AccessLimitAspect {

    private static final String LIMITING_KEY = "limiting:%s:%s";
    private static final String LIMITING_BEGINTIME = "beginTime";
    private static final String LIMITING_EXFREQUENCY = "exFrequency";

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Pointcut("@within(com.svse.annotation.AccessLimit) || @annotation(com.svse.annotation.AccessLimit)")
    @Order(1)
    public void accessLimit(){}

    @Around("accessLimit()")
    public Object doAround(ProceedingJoinPoint point) throws Throwable {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();

            //获取请求的ip和方法
            String ipAddress = IPUtils.getIpAddr(request);
            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            String methodName = method.getName();
            AccessLimit accessLimit = method.getAnnotation(AccessLimit.class);

            //获取方法的访问周期和频率
            long cycle = accessLimit.cycle();
            int frequency = accessLimit.frequency();
            long currentTime = System.currentTimeMillis();

            //获取redis中周期内第一次访问方法的时间和执行的次数
            Long beginTimeLong = (Long) redisTemplate.opsForHash().get(String.format(LIMITING_KEY, ipAddress, methodName), LIMITING_BEGINTIME);
            Integer exFrequencyLong = (Integer) redisTemplate.opsForHash().get(String.format(LIMITING_KEY, ipAddress, methodName), LIMITING_EXFREQUENCY);

            long beginTime = beginTimeLong == null ? 0L : beginTimeLong;
            int exFrequency = exFrequencyLong == null ? 0 : exFrequencyLong;
            //如果当前时间减去周期内第一次访问方法的时间大于周期时间，则正常访问
            //并将周期内第一次访问方法的时间和执行次数初始化
            if (currentTime - beginTime > cycle) {
                redisTemplate.opsForHash().put(String.format(LIMITING_KEY, ipAddress, methodName), LIMITING_BEGINTIME, currentTime);
                redisTemplate.opsForHash().put(String.format(LIMITING_KEY, ipAddress, methodName), LIMITING_EXFREQUENCY, 1);
                redisTemplate.expire(String.format(LIMITING_KEY, ipAddress, methodName), accessLimit.expireTime(), TimeUnit.SECONDS);
                return point.proceed();
            } else {
                //如果在周期时间内，执行次数小于频率，则正常访问
                //并将执行次数加一
                if (exFrequency < frequency) {
                    redisTemplate.opsForHash().put(String.format(LIMITING_KEY, ipAddress, methodName), LIMITING_EXFREQUENCY, exFrequency + 1);
                    redisTemplate.expire(String.format(LIMITING_KEY, ipAddress, methodName), accessLimit.expireTime(), TimeUnit.SECONDS);
                    return point.proceed();
                } else {
                    //否则抛出访问频繁异常
                    return "{\"code\":\"502\",\"message\":"+accessLimit.message()+"\"\"}";
                }
            }
    }
}
